/**
 * 
 */
package com.bodystm.temperature.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bodystm.temperature.bed.Bed;
import com.bodystm.temperature.bed.BedService;
import com.bodystm.temperature.concentrator.Concentrator;
import com.bodystm.temperature.concentrator.ConcentratorService;
import com.bodystm.temperature.server.Temperature;
import com.bodystm.temperature.web.ConcentratorDevice;
import com.bodystm.temperature.web.DeviceSettings;
import com.bodystm.temperature.web.TemperatureDevice;
import com.mimosa.common.system.user.TUser;
import com.mimosa.common.system.user.UserContext;
import com.mimosa.util.config.Page;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author a
 *
 */
@Controller
@RequestMapping("/concentrator")
public class ConcentratorController {
	@Resource
	private BedService bedService;
	@Resource
	private ConcentratorService concentratorService;
	
	@ResponseBody
	@RequestMapping("/list.action")
	public String list(Page<Concentrator> page) {
		//page = this.patientService.findByPage(page);
		Page<Concentrator> concentrators;
		concentrators=concentratorService.findByPage(page);
		StringBuilder builder = new StringBuilder("{\"total\":\"");
		builder.append(concentrators.getTotalCount());
		builder.append("\",\"rows\":[");
		for (Concentrator concentrator : concentrators.getResult()) {
			builder.append("{\"id\":\"").append(concentrator.getId());
			builder.append("\",\"bedName\":\"").append(concentrator.getBedName());
			builder.append("\",\"signaled\":\"").append(concentrator.getStatus());
			builder.append("\",\"concentratorNo\":\"").append(concentrator.getConcentratorNo()).append("\"},");
		}
		if(concentrators.getResult().size()>0)
		builder.deleteCharAt(builder.length() - 1);
		builder.append("]}");
		return builder.toString();
	}
	
	@ResponseBody
	@RequestMapping("/delete.action")
	public String delete(Concentrator concentrator,HttpSession session) {
		Concentrator con=this.concentratorService.getEntity(concentrator.getId());
		if(con!=null){
			concentratorService.deleteEntity(concentrator);
		}
		return "{\"success\":true,\"bedid\":\""+concentrator.getBedName()+"\"}";
	}	
	
	/**
	 * 添加或者修改集中器信息
	 * @param concentrator
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/add.action")
	public String add(Concentrator concentrator,HttpSession session) {
		if(concentrator.getId()!=null&&concentrator.getId().length()>0){//修改记录
			Concentrator con=this.concentratorService.getEntity(concentrator.getId());
			java.util.List<Concentrator> lstCons=this.concentratorService.findList("from Concentrator t where  t.bedName=? and t.user.id=?", concentrator.getBedName(),((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
			if(lstCons.size()>0&&!concentrator.getId().equals(lstCons.get(0).getId())){
				return "{\"success\":false,\"bedid\":\""+concentrator.getBedName()+"\"}";
			}
			con.setBedName(concentrator.getBedName());
			con.setConcentratorNo(concentrator.getConcentratorNo().toUpperCase());
			this.concentratorService.updateEntity(con);
		}else{
			concentrator.setUser((TUser)session.getAttribute(UserContext.USER_ATTR));
			concentrator.setStatus(1);
			concentrator.setConcentratorNo(concentrator.getConcentratorNo().toUpperCase());
			this.concentratorService.saveEntity(concentrator);
		}
		return "{\"success\":true,\"bedid\":\""+concentrator.getBedName()+"\"}";
	}	
	
	@ResponseBody
	@RequestMapping("/getNosignedConcentrator.action")
	public String getNosignedConcentrator(String userId,HttpSession session){
		/*ConcentratorDevice concentratorDevice=null;
		List<Temperature> lstTemperature=null;
		JSONArray jSONArray = new JSONArray();
		JSONObject jSONObject = null;
		StringBuilder strBuilder=new StringBuilder();
		for(int i=0;i<DeviceSettings.lstMacs4Concentrator.size();i++){
			concentratorDevice=(ConcentratorDevice) DeviceSettings.hasDevice4Concentrator.get(DeviceSettings.lstMacs4Concentrator.get(i));
			if(concentratorDevice==null)continue;
			if(concentratorDevice.isWarningOrNot()&&!concentratorDevice.isSignaled()){
				strBuilder.append(concentratorDevice.getConcentratorNo()+",");
				
			}
		}
		if(strBuilder.length()>0)
		strBuilder.deleteCharAt(strBuilder.length() - 1);
		jSONObject = new JSONObject();
		jSONObject.put("ConcentratorNo", strBuilder);
		return strBuilder.toString();*/
		/*ConcentratorDevice concentratorDevice=null;
		List<Temperature> lstTemperature=null;
		JSONArray jSONArray = new JSONArray();
		JSONObject jSONObject = null;
		StringBuilder strBuilder=new StringBuilder();
		List<Bed> lstBeds=bedService.getNotEmptyBeds4CheckConcentrator(userId);
		String concentratorNo="";
		List<String> theConcentratorNos=new ArrayList<String>();//避免同一个集中器重复报警
		for(int i=0;i<lstBeds.size();i++){
			concentratorNo=lstBeds.get(i).getConcentratorNo();
			if(lstBeds.contains(concentratorNo))continue;
			theConcentratorNos.add(concentratorNo);
			if(DeviceSettings.lstMacs4Concentrator.contains(concentratorNo)){
				concentratorDevice=(ConcentratorDevice) DeviceSettings.hasDevice4Concentrator.get(DeviceSettings.lstMacs4Concentrator.get(i));
			}else{
				DeviceSettings.lstMacs4Concentrator.add(concentratorNo);
				concentratorDevice=new ConcentratorDevice();
				concentratorDevice.setConcentratorNo(concentratorNo);
				DeviceSettings.hasDevice4Concentrator.put(concentratorNo, concentratorDevice);
			}
			if(concentratorDevice.isWarningOrNot()&&!concentratorDevice.isSignaled()){
				strBuilder.append(concentratorDevice.getConcentratorNo()+",");
				
			}
		}
		if(strBuilder.length()>0)
			strBuilder.deleteCharAt(strBuilder.length() - 1);
			jSONObject = new JSONObject();
			jSONObject.put("ConcentratorNo", strBuilder);
			return strBuilder.toString();*/
		JSONObject json=new JSONObject();
		List<Concentrator> lstConcentrators=concentratorService.findList(Restrictions.eq("user.id", ((TUser)session.getAttribute(UserContext.USER_ATTR)).getId()));
		List<String> lstConcentratorNos=new ArrayList<String>();
		for(Concentrator con : lstConcentrators){
			if(!lstConcentratorNos.contains(con.getConcentratorNo()))
				lstConcentratorNos.add(con.getConcentratorNo());
			
		}
		ConcentratorDevice concentratorDevice=null;
		StringBuilder strBuilder=new StringBuilder();
		StringBuilder strBuilder4Macs=new StringBuilder();
		for(int i=0;i<DeviceSettings.lstMacs4Concentrator.size();i++){
			if(!lstConcentratorNos.contains(DeviceSettings.lstMacs4Concentrator.get(i))){
				continue;
			}
			concentratorDevice=(ConcentratorDevice) DeviceSettings.hasDevice4Concentrator.get(DeviceSettings.lstMacs4Concentrator.get(i));
			if(concentratorDevice.isWarningOrNot()&&!concentratorDevice.isSignaled()){
				strBuilder.append(concentratorDevice.getBedName()+",");//concentratorDevice.getConcentratorNo()
				strBuilder4Macs.append(concentratorDevice.getConcentratorNo()+",");
			}
		}
		if(strBuilder.length()>0){
			strBuilder.deleteCharAt(strBuilder.length() - 1);
			strBuilder4Macs.deleteCharAt(strBuilder4Macs.length() - 1);
			json.put("success", true);
			json.put("bedName", strBuilder.toString());
			json.put("macs", strBuilder4Macs.toString());
		}else{
			json.put("success", false);
			
		}
		return json.toString();	
	}
	
	
	@ResponseBody
	@RequestMapping("/stopwarning.action")
	public String stopwarning(String strmacs){
		try {
			String[] strs=strmacs.split(",");
			if(strs==null)return Boolean.FALSE.toString().toLowerCase();
			for(int i=0;i<strs.length;i++){
				if(DeviceSettings.lstMacs4Concentrator.contains(strs[i])){
					ConcentratorDevice concentratorDevice=(ConcentratorDevice)DeviceSettings.hasDevice4Concentrator.get(strs[i]);
					concentratorDevice.setWarningOrNot(false);
					
				}
			}
			return Boolean.TRUE.toString().toLowerCase();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Boolean.FALSE.toString().toLowerCase();
		}	
	}
}
